<template>
  <CommonLayout
    pageTitle="交易管理"
    sidebarTitle="交易筛选"
    :loading="loading"
    :isEmpty="transactions.length === 0 && !loading"
    emptyText="暂无交易数据"
  >
    <!-- 侧边栏筛选区 -->
    <template #sidebar>
      <form class="filter-form" @submit.prevent="handleFilter">
        <div class="filter-item">
          <label>关键字搜索</label>
          <input
            v-model="filterForm.keyword"
            placeholder="商品名称/订单号"
            class="filter-input"
          />
        </div>

        <div class="filter-item">
          <label>交易状态</label>
          <select v-model="filterForm.status" class="filter-select">
            <option value="">全部状态</option>
            <option value="0">待付款</option>
            <option value="1">已付款</option>
            <option value="2">已发货</option>
            <option value="3">已收货</option>
            <option value="4">已完成</option>
            <option value="5">已取消</option>
          </select>
        </div>

        <div class="filter-item">
          <label>时间排序</label>
          <select v-model="filterForm.sortByTime" class="filter-select">
            <option value="">默认排序</option>
            <option value="created_at_asc">创建时间升序</option>
            <option value="created_at_desc">创建时间降序</option>
          </select>
        </div>

        <div class="filter-item">
          <label>金额排序</label>
          <select v-model="filterForm.sortByAmount" class="filter-select">
            <option value="">默认排序</option>
            <option value="amount_asc">金额升序</option>
            <option value="amount_desc">金额降序</option>
          </select>
        </div>

        <button type="submit" class="filter-btn">应用筛选</button>
        <button
          type="button"
          class="reset-btn"
          @click="resetFilter"
        >
          重置筛选
        </button>
      </form>
    </template>

    <!-- 主内容区 -->
    <template #content>
      <div class="transaction-table-container">
        <table class="product-table">
          <thead>
            <tr>
              <th>订单编号</th>
              <th>商品名称</th>
              <th>买家</th>
              <th>金额</th>
              <th>创建时间</th>
              <th>状态</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="transaction in transactions" :key="transaction.order_id" class="product-row">
              <td>{{ transaction.order_id }}</td>
              <td>{{ transaction.product_name }}</td>
              <td>{{ transaction.buyer_name }}</td>
              <td>￥{{ transaction.amount.toFixed(2) }}</td>
              <td>{{ formatDate(transaction.created_at) }}</td>
              <td>
                <span :class="['status-tag', getStatusClass(transaction.status)]">
                  {{ getStatusText(transaction.status) }}
                </span>
              </td>
              <td class="action-buttons">
                <button
                  class="btn-common btn查看"
                  @click="viewTransactionDetail(transaction)"
                >
                  查看
                </button>
                <button
                  v-if="transaction.status === 1"
                  class="btn-common btn发货"
                  @click="handleShip(transaction.order_id)"
                >
                  发货
                </button>
              </td>
            </tr>
          </tbody>
        </table>

        <!-- 分页组件 -->
        <div class="pagination-container">
          <div class="pagination-info">
            共 {{totalPages}} 页，当前第 {{currentPage}} 页，每页 {{pageSize}} 条
          </div>
          <div class="pagination-buttons">
            <button @click="prevPage" :disabled="currentPage === 1" class="pagination-btn">上一页</button>
            <button
              v-for="page in pageRange"
              :key="page"
              @click="goToPage(page)"
              :class="{ 'pagination-btn': true, 'active': page === currentPage }"
            >
              {{ page }}
            </button>
            <button @click="nextPage" :disabled="currentPage === totalPages" class="pagination-btn">下一页</button>
          </div>
        </div>
      </div>
    </template>
  </CommonLayout>

  <!-- 查看交易详情模态框 -->
  <div v-if="showViewModal" class="approve-modal-overlay" @click="closeViewModal">
    <div class="approve-modal" @click.stop>
      <div class="modal-header">
        <h3>交易详情 - 订单号: {{ viewedTransaction?.order_id }}</h3>
        <button class="close-btn" @click="closeViewModal">&times;</button>
      </div>
      <div class="modal-body">
        <div v-if="loadingViewDetail" class="loading">加载中...</div>
        <div v-else-if="!viewedTransaction" class="error-message">获取交易详情失败</div>
        <div v-else class="transaction-detail">
          <div class="product-info">
            <p><strong>订单编号:</strong> {{ viewedTransaction.order_id }}</p>
            <p><strong>商品名称:</strong> {{ viewedTransaction.product_name }}</p>
            <p><strong>商品价格:</strong> ¥{{ viewedTransaction.price.toFixed(2) }}</p>

            <p><strong>总金额:</strong> ¥{{ viewedTransaction.amount.toFixed(2) }}</p>
            <p><strong>买家:</strong> {{ viewedTransaction.buyer_name }}</p>
            <p><strong>联系电话:</strong> {{ viewedTransaction.phone }}</p>
            <p><strong>收货地址:</strong> {{ viewedTransaction.address }}</p>
            <p><strong>订单状态:</strong> {{ getStatusText(viewedTransaction.status) }}</p>
            <p><strong>创建时间:</strong> {{ formatDate(viewedTransaction.created_at) }}</p>
            <p v-if="viewedTransaction.pay_time"><strong>支付时间:</strong> {{ formatDate(viewedTransaction.pay_time) }}</p>
            <p v-if="viewedTransaction.ship_time"><strong>发货时间:</strong> {{ formatDate(viewedTransaction.ship_time) }}</p>
            <p v-if="viewedTransaction.complete_time"><strong>完成时间:</strong> {{ formatDate(viewedTransaction.complete_time) }}</p>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 发货模态框 -->
  <div v-if="showShipModal" class="approve-modal-overlay" @click="closeShipModal">
    <div class="approve-modal" @click.stop>
      <div class="modal-header">
        <h3>发货 - 订单号: {{ currentOrderId }}</h3>
        <button class="close-btn" @click="closeShipModal">&times;</button>
      </div>
      <div class="modal-body">
        <div class="form-group">
          <label>物流公司</label>
          <input
            v-model="shippingForm.company"
            placeholder="请输入物流公司"
            class="filter-input"
          />
        </div>
        <div class="form-group">
          <label>物流单号</label>
          <input
            v-model="shippingForm.trackingNumber"
            placeholder="请输入物流单号"
            class="filter-input"
          />
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn-common btn-reject" @click="closeShipModal">取消</button>
        <button class="btn-common btn-approve" @click="confirmShip">确认发货</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed } from 'vue';
import axios from 'axios';
import moment from 'moment';
import CommonLayout from '../components/CommonLayout.vue';

// 分页相关状态
const currentPage = ref(1);
const totalPages = ref(1);
const pageSize = ref(10); // 每页显示10条数据

// 查看详情相关状态
const showViewModal = ref(false);
const viewedTransaction = ref<Transaction | null>(null);
const loadingViewDetail = ref(false);

// 发货相关状态
const showShipModal = ref(false);
const currentOrderId = ref('');
const shippingForm = reactive<{
  company: string;
  trackingNumber: string;
}>({
  company: '',
  trackingNumber: ''
});

/**
 * 获取页码范围，用于显示分页按钮
 * @returns 页码数组
 */
const pageRange = computed(() => {
  const range = [];
  const maxVisiblePages = 5; // 最多显示5个页码按钮
  let startPage = Math.max(1, currentPage.value - Math.floor(maxVisiblePages / 2));
  let endPage = startPage + maxVisiblePages - 1;

  if (endPage > totalPages.value) {
    endPage = totalPages.value;
    startPage = Math.max(1, endPage - maxVisiblePages + 1);
  }

  for (let i = startPage; i <= endPage; i++) {
    range.push(i);
  }

  return range;
});

/**
 * 跳转到上一页
 */
const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--;
    fetchTransactions();
  }
};

/**
 * 跳转到下一页
 */
const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++;
    fetchTransactions();
  }
};

/**
 * 跳转到指定页码
 * @param page 目标页码
 */
const goToPage = (page: number) => {
  if (page !== currentPage.value && page >= 1 && page <= totalPages.value) {
    currentPage.value = page;
    fetchTransactions();
  }
};

/**
 * 定义交易接口类型
 */
interface Transaction {
  order_id: string;
  product_id: number;
  product_name: string;
  buyer_id: number;
  buyer_name: string;
  price: number;
  amount: number;
  status: number;
  created_at: string;
  pay_time?: string;
  ship_time?: string;
  complete_time?: string;
  phone: string;
  address: string;
}

// 状态管理
const transactions = ref<Transaction[]>([]);
const loading = ref<boolean>(false);

// 筛选表单数据
const filterForm = reactive<{
  keyword: string;
  sortByTime: string;
  sortByAmount: string;
  status: string;
}>({
  keyword: '',
  sortByTime: '',
  sortByAmount: '',
  status: ''
});

/**
 * 获取交易列表数据
 */
const fetchTransactions = async () => {
  loading.value = true;
  try {
    const token = localStorage.getItem('token');
    // 构建筛选参数
    const params = {
      keyword: filterForm.keyword || undefined,
      status: filterForm.status || undefined,
      sortByTime: filterForm.sortByTime || undefined,
      sortByAmount: filterForm.sortByAmount || undefined,
      page: currentPage.value,
      pageSize: pageSize.value
    };

    // 前端日志：记录请求参数
    console.log(`[${new Date().toISOString()}] [INFO] 交易列表请求参数: ${JSON.stringify(params)}`);

    const response = await axios.get('/api/admin/transactions', {
      headers: { Authorization: `Bearer ${token}` },
      params,
    });

    // 前端日志：记录响应结果
    console.log(`[${new Date().toISOString()}] [INFO] 交易列表响应结果: ${JSON.stringify(response.data)}`);

    // 更新分页信息
    totalPages.value = response.data.pagination?.totalPages || 1;
    console.log(`[${new Date().toISOString()}] [DEBUG] 分页信息: totalPages=${totalPages.value}, currentPage=${currentPage.value}, pageRange=${JSON.stringify(pageRange.value)}`);
    
    transactions.value = (response.data.transactions as Transaction[]).map((transaction: Transaction) => ({
      ...transaction,
      price: isNaN(Number(transaction.price)) ? 0 : Number(transaction.price),
      amount: isNaN(Number(transaction.amount)) ? 0 : Number(transaction.amount)
    })) || [];
  } catch (error: any) {
    console.error(`[${new Date().toISOString()}] [ERROR] 获取交易列表失败:`, error);
    alert(`获取交易列表失败: ${error.message}`);
    transactions.value = [];
    totalPages.value = 1;
  } finally {
    loading.value = false;
  }
};

/**
 * 处理筛选提交
 */
const handleFilter = () => {
  // 重置页码为第一页
  currentPage.value = 1;
  fetchTransactions();
};

/**
 * 重置筛选条件
 */
const resetFilter = () => {
  filterForm.keyword = '';
  filterForm.sortByTime = '';
  filterForm.sortByAmount = '';
  filterForm.status = '';
  currentPage.value = 1;
  fetchTransactions();
};

/**
 * 查看交易详情
 * @param transaction 要查看的交易
 */
const viewTransactionDetail = async (transaction: Transaction) => {
  showViewModal.value = true;
  loadingViewDetail.value = true;
  try {
    const token = localStorage.getItem('token');
    console.log(`[${new Date().toISOString()}] [INFO] [查看交易详情] 获取交易详情: orderId=${transaction.order_id}`);
    const response = await axios.get(`/api/admin/transactions/${transaction.order_id}`, {
      headers: { Authorization: `Bearer ${token}` }
    });
    viewedTransaction.value = response.data.transaction;
    // 确保价格和金额是数字类型
    if (viewedTransaction.value) {
      viewedTransaction.value.price = isNaN(Number(viewedTransaction.value.price)) ? 0 : Number(viewedTransaction.value.price);
      viewedTransaction.value.amount = isNaN(Number(viewedTransaction.value.amount)) ? 0 : Number(viewedTransaction.value.amount);
    }
    console.log(`[${new Date().toISOString()}] [INFO] [查看交易详情] 交易详情获取成功: orderId=${transaction.order_id}`);
  } catch (error) {
    console.error(`[${new Date().toISOString()}] [ERROR] [查看交易详情] 获取交易详情失败:`, error);
    alert('获取交易详情失败');
  } finally {
    loadingViewDetail.value = false;
  }
};

/**
 * 关闭交易详情模态框
 */
const closeViewModal = () => {
  showViewModal.value = false;
  viewedTransaction.value = null;
};

/**
 * 打开发货模态框
 * @param orderId 订单ID
 */
const handleShip = (orderId: string) => {
  currentOrderId.value = orderId;
  shippingForm.company = '';
  shippingForm.trackingNumber = '';
  showShipModal.value = true;
};

/**
 * 关闭发货模态框
 */
const closeShipModal = () => {
  showShipModal.value = false;
  currentOrderId.value = '';
};

/**
 * 确认发货
 */
const confirmShip = async () => {
  if (!currentOrderId.value || !shippingForm.company || !shippingForm.trackingNumber) {
    alert('请填写完整的物流信息');
    return;
  }

  try {
    const token = localStorage.getItem('token');
    console.log(`[${new Date().toISOString()}] [INFO] [发货] 订单发货: orderId=${currentOrderId.value}`);
    await axios.put(`/api/admin/transactions/${currentOrderId.value}/ship`, {
      company: shippingForm.company,
      tracking_number: shippingForm.trackingNumber
    }, {
      headers: { Authorization: `Bearer ${token}` }
    });
    alert('发货成功');
    console.log(`[${new Date().toISOString()}] [SUCCESS] [发货] 订单发货成功: orderId=${currentOrderId.value}`);
    closeShipModal();
    fetchTransactions(); // 重新获取交易列表
  } catch (error: any) {
    console.error(`[${new Date().toISOString()}] [ERROR] [发货] 订单发货失败:`, error);
    alert(`发货失败: ${error.message}`);
  }
};

/**
 * 格式化日期
 * @param dateString 日期字符串
 * @returns 格式化后的日期字符串
 */
const formatDate = (dateString: string) => {
  return moment(dateString).format('YYYY-MM-DD HH:mm:ss');
};

/**
 * 根据状态获取对应的CSS类
 * @param status 交易状态
 * @returns CSS类名
 */
const getStatusClass = (status: number) => {
  switch (status) {
    case 0:
      return 'status-pending';
    case 1:
      return 'status-active';
    case 2:
      return 'status-shipped';
    case 3:
      return 'status-received';
    case 4:
      return 'status-completed';
    case 5:
      return 'status-canceled';
    default:
      return 'status-inactive';
  }
};

/**
 * 根据状态获取对应的文本
 * @param status 交易状态
 * @returns 状态文本
 */
const getStatusText = (status: number) => {
  switch (status) {
    case 0:
      return '待付款';
    case 1:
      return '已付款';
    case 2:
      return '已发货';
    case 3:
      return '已收货';
    case 4:
      return '已完成';
    case 5:
      return '已取消';
    default:
      return '未知状态';
  }
};

// 页面加载时初始化数据
onMounted(() => {
  console.log(`[${new Date().toISOString()}] [INFO] [交易管理] 组件已挂载，开始获取数据`);
  fetchTransactions();
});
</script>

<style scoped>
/* 复用商品管理页面的样式 */
.filter-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.filter-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.filter-input, .filter-select {
  width: 100%;
  padding: 8px;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  font-size: 14px;
}

.filter-btn {
  padding: 8px;
  background: #2563eb;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
}

.reset-btn {
  padding: 8px;
  background: #f1f5f9;
  color: #334155;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
}

.transaction-table-container {
  overflow-x: auto;
}

.product-table {
  width: 100%;
  border-collapse: collapse;
  text-align: left;
}

.product-table th, .product-table td {
  padding: 12px 16px;
  border-bottom: 1px solid #e2e8f0;
}

.product-table th {
  background-color: #f8fafc;
  font-weight: 600;
  color: #1e293b;
}

.product-row:hover {
  background-color: #f8fafc;
}

.status-tag {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-active {
  background-color: #d1fae5;
  color: #065f46;
}

.status-pending {
  background-color: #fef3c7;
  color: #92400e;
}

.status-shipped {
  background-color: #dbeafe;
  color: #1e40af;
}

.status-received {
  background-color: #e0f2fe;
  color: #0284c7;
}

.status-completed {
  background-color: #e0f2fe;
  color: #0369a1;
}

.status-canceled {
  background-color: #fee2e2;
  color: #b91c1c;
}

.status-inactive {
  background-color: #f3f4f6;
  color: #6b7280;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.btn-common {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.btn查看 {
  background-color: #3b82f6;
  color: white;
}

.btn发货 {
  background-color: #10b981;
  color: white;
}

.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #e2e8f0;
}

.pagination-info {
  color: #64748b;
  font-size: 14px;
}

.pagination-buttons {
  display: flex;
  gap: 8px;
}

.pagination-btn {
  padding: 6px 12px;
  border: 1px solid #e2e8f0;
  border-radius: 4px;
  background-color: white;
  color: #334155;
  cursor: pointer;
}

.pagination-btn.active {
  background-color: #2563eb;
  color: white;
  border-color: #2563eb;
}

.pagination-btn:disabled {
  cursor: not-allowed;
  opacity: 0.5;
}

/* 模态框样式 */
.approve-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.approve-modal {
  background-color: white;
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
  max-height: 80vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #e2e8f0;
}

.modal-header h3 {
  margin: 0;
  color: #1e293b;
  font-size: 18px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #64748b;
}

.modal-body {
  padding: 16px;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px;
  border-top: 1px solid #e2e8f0;
}

.btn-reject {
  background-color: #f1f5f9;
  color: #334155;
}

.btn-approve {
  background-color: #2563eb;
  color: white;
}

.transaction-detail {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.product-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.loading {
  text-align: center;
  padding: 48px;
  color: #64748b;
  font-size: 16px;
}

.error-message {
  text-align: center;
  padding: 48px;
  color: #ef4444;
  font-size: 16px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 16px;
}
</style>